<template>
  <ag-grid
    :column-defs="columnDefs"
    :gridOptions="gridOptions"
    :id="tableId"
    :row-data="rows"
    :style="{ height }"
    @grid-ready="setGridApi"
    :dark="dark"
    :dense="false"
    @first-data-rendered="gridApi?.sizeColumnsToFit()"
    :components="{ buttonRenderer: 'ConfirmButton' }"
  />
</template>
<!-- style="background-color: #272032" -->

<script lang="ts">
import { useQuasar } from 'quasar';
import { api } from 'src/boot/api';

import { useGridApi } from 'src/boot/grid';
import AgGrid from 'src/components/ag-grid/index.vue';
import { useFilter } from 'src/components/filter/hooks';
import { useEmitter } from 'src/emitter';
import { defineComponent } from 'vue';
import ConfirmButton from './confirm-button.vue';
import { Row } from './models';
import { createColumnDefs, createGridOptions } from './services';

export default defineComponent({
  name: 'main-table',

  components: {
    AgGrid,
    //eslint-disable-next-line vue/no-unused-components
    ConfirmButton,
  },

  props: {
    craneId: {
      type: String,
      required: true,
    },
    tableId: {
      type: String,
      required: true,
    },
    height: {
      type: String,
    },
    rows: {
      type: Array,
    },
    dark: {
      type: Boolean,
      required: true,
    },
  },

  setup(props) {
    const $q = useQuasar();
    const [gridApi, setGridApi] = useGridApi<Row>();

    useEmitter('inform', async payload => {
      if (payload.name !== 'terminal-crane-toolbar' && payload.name !== 'terminal-crane-orderTypeClick') {
        return;
      }

      if (payload.value === '指令起吊') {
        const selectedRow = props.rows?.filter((v: any) => v.orderStatus == '11');
        if (!selectedRow || selectedRow.length === 0) {
          return $q.notify({ message: '请先选中一条指令', color: 'negative' });
        }
        selectedRow?.forEach((element: any) => {
          api.get(
            `/ManalController/CraneOrderOperate?craneNo=1&orderNo=${element.orderNo}&operType=1&currentPos=${element.frPos}`,
          );
        });
      } else if (payload.value === '指令卸下') {
        const selectedRow = props.rows?.filter((v: any) => v.orderStatus == '13');
        if (!selectedRow || selectedRow.length === 0) {
          return $q.notify({ message: '请先起吊一条指令', color: 'negative' });
        }
        selectedRow.forEach((element: any) => {
          api.get(
            `/ManalController/CraneOrderOperate?craneNo=1&orderNo=${element.orderNo}&operType=2&currentPos=${element.frPos}`,
          );
        });
      } else {
        return;
      }
    });

    useFilter(gridApi);

    return {
      gridApi,
      setGridApi,
      columnDefs: createColumnDefs(),
      gridOptions: createGridOptions(),
    };
  },
});
</script>
